#!/opt/chef/embedded/bin/ruby
require 'zk'
require 'json'
require 'erubis'

def usage(exitcode)
    puts "Usage:  scripts/cleanzk.rb <deployment-name> [zkserver] [zkport]"
    exit exitcode
end


dname = ARGV[0]
zkserver="9.55.48.67"
zkport="2181"
if dname == nil 
	puts "Need one argument to tell me what deployment to clean up."
	usage(1);
end

input = File.read('nodes/nodetemplate.json')
eruby = Erubis::Eruby.new(input)
json = File.read("deployments/conf/#{dname}.json")
depl = JSON.parse(json)

puts "Connecting to ZK at #{depl['zookeeperurl']}"

puts "Listing /deployments/#{dname}"
zk = ZK.new("#{depl['zookeeperurl']}")
begin
	zk.find("/deployments/#{dname}") do | path|

		data = zk.get(path).first
		begin
        	if data and not data.empty?
				puts ""
				puts "#{path} :=> "
				jsonData = JSON.parse(data)
				#puts jsonData
				jsonData.each do | element | 
					# Show the zk data created by startinstr/stopinstr
					begin
						stage = element['stage']
						start = element['start']
						stop =  element['stop']
						puts "\tstage=>#{stage}"	
						puts "\t\tstart=>#{start}; stop=>#{stop}"	
					rescue
						# Not a startinstr/stopinstr 	
					end
				end
        	end
      	rescue
        	#not a leaf node? 
      	end
	end
rescue 
	puts "The deployment #{dname} does not have any zookeeper entries"
end
	
  
